package com.campus.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.campus.entity.*;
import com.campus.entity.bo.StudentAttendanceInfoBO;
import com.campus.entity.vo.CheckInUserVO;
import com.campus.mapper.BuildingMapper;
import com.campus.mapper.CheckInMapper;
import com.campus.mapper.DormitoryMapper;
import com.campus.mapper.StudentMapper;
import com.campus.util.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;

@RestController
public class DormitoryController {

    @Autowired
    private DormitoryMapper dormitoryMapper;
    @Autowired
    private BuildingMapper buildingMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ExcelUtil excelUtil;


    @RequestMapping("/resident/{admin}")
    public ResultBody resident(@PathVariable("admin") String admin,@RequestBody Map<String,Long> time){
        long divi=24*60*60*1000;
        long timestamp = time.get("timestamp")*1000;
        System.out.println(timestamp);
        Date dateBegin = new Date(timestamp / divi * divi);
        Date dateEnd = new Date(timestamp/divi*divi+divi);
        Integer buildingNo = buildingMapper.selectOne(new QueryWrapper<BuildingEntity>().eq("building_admin", admin)).getBuildingNo();
        List<DormitoryEntity> residents = dormitoryMapper.selectList(new QueryWrapper<DormitoryEntity>().eq("building_no", buildingNo));
        Map<String,Map<String, Map<String, CheckInUserVO>>> data = new HashMap<>();
        for (DormitoryEntity entity : residents) {
            Map<String, Map<String, CheckInUserVO>> mapDoorplate = data.computeIfAbsent(entity.getFloor().toString(), k -> new HashMap<>());
            Map<String, CheckInUserVO> bed = mapDoorplate.computeIfAbsent(entity.getDoorplate().toString(), k -> new HashMap<>());
            Student account = studentMapper.selectOne(new QueryWrapper<Student>().eq("account", entity.getAccount()));
            //判断条件未写完，应该只查询当天的添加的数据
            bed.put(entity.getBedNo().toString(),new CheckInUserVO(checkInMapper.selectOne(new QueryWrapper<SignInEntity>().eq("account",entity.getAccount()).ge("date",dateBegin).lt("date",dateEnd))!=null
                    ,studentMapper.selectOne(new QueryWrapper<Student>().eq("account",entity.getAccount())
                    )));
        }
        return ResultBody.ok().data("data",data);
    }

    @RequestMapping("/resident/download/{admin}")
    public ResultBody download(@PathVariable("admin") String admin,@RequestBody Map<String,Long> time) throws IOException {
        System.out.println(time);
        long divi=24*60*60*1000;
        long timestamp = time.get("timestamp")*1000;
        Date dateBegin = new Date(timestamp /divi * divi);
        Date dateEnd = new Date(timestamp/divi*divi+divi);
        BuildingEntity building_admin = buildingMapper.selectOne(new QueryWrapper<BuildingEntity>().eq("building_admin", admin));
        Integer buildingNo = building_admin.getBuildingNo();
        List<String> studentId = dormitoryMapper.selectList(new QueryWrapper<DormitoryEntity>().eq("building_no", buildingNo)).stream().map(DormitoryEntity::getAccount).collect(Collectors.toList());
        List<Student> studentsInfo = studentMapper.selectList(new QueryWrapper<Student>().in("account", studentId));
        List<StudentAttendanceInfoBO> data = new ArrayList<>();
        for(Student s:studentsInfo){
            StudentAttendanceInfoBO infoBO = new StudentAttendanceInfoBO();
            BeanUtil.copyProperties(s,infoBO);
            SignInEntity account = checkInMapper.selectOne(new QueryWrapper<SignInEntity>().eq("account", s.getAccount()).ge("date",dateBegin).le("date",dateEnd));
            if(account==null){
                infoBO.setStatus("已打卡");
            }else{
                infoBO.setStatus("暂未打卡");
            }
            data.add(infoBO);
        }
        String excelPath = excelUtil.generateExcel(data, building_admin.getBuildingName()+"寝室打卡出勤表");
        return ResultBody.ok().data("path",excelPath);
    }

    @RequestMapping("/signin/add/{account}")
    public ResultBody signIn(@PathVariable("account") String account){
        DormitoryEntity info = dormitoryMapper.selectOne(new QueryWrapper<DormitoryEntity>().eq("account", account));
        checkInMapper.insert(new SignInEntity(info.getAccount(), info.getBuildingNo(),info.getFloor(),info.getDoorplate(),info.getBedNo(),new Date(System.currentTimeMillis())));
        return ResultBody.ok();
    }
}
